package service

import (
	"gitee.com/sunny-zhangqiang/zcache_new/comm"
	"gitee.com/sunny-zhangqiang/zcache_new/config"
	"gitee.com/sunny-zhangqiang/zcache_new/logger"
	"gitee.com/sunny-zhangqiang/zcache_new/ztp"
	"net"
	"sync/atomic"
	"time"
)

var (
	be = comm.BE
)

func doProbProcess(c net.Conn) {
	clientToken := ""

	defer c.Close()
	defer func() {
		if clientToken == "" {
			return
		}
		mge.clientAbort(clientToken)
		cm.clientAbort(clientToken)
	}()

	lenBuf := make([]byte, 4)
	msgBuf := make([]byte, 1024)
	sendBuf := make([]byte, len(serverToken)+1)
	copy(sendBuf[1:], serverToken)

	for {
		d := time.Now().Add(time.Millisecond * time.Duration(config.ServerConf.ProbTimeoutMSec))
		c.SetDeadline(d)

		lenBuf = lenBuf[:4]
		err := ztp.ReadN(c, lenBuf, 4)
		if err != nil {
			logger.Error("client %s read msg len failed, err: %s",
				c.RemoteAddr().String(), err.Error())
			break
		}

		msgLen := be.Uint32(lenBuf)
		if msgLen < 4 || msgLen > 1000 {
			logger.Error("client %s send msg len not as expected",
				c.RemoteAddr().String())
			break
		}

		msgBuf = msgBuf[:msgLen]
		err = ztp.ReadN(c, msgBuf, int(msgLen))
		if err != nil {
			logger.Error("client %s read msg failed, err: %s",
				c.RemoteAddr().String(), err.Error())
			break
		}

		msgToken := string(msgBuf)
		if msgToken == "" {
			logger.Error("client %s token is nil",
				c.RemoteAddr().String())
		}

		if clientToken == "" {
			clientToken = msgToken
		} else {
			if msgToken != clientToken {
				logger.Error("client %s token changes",
					c.RemoteAddr().String())
				break
			}
		}

		active := 1
		if atomic.LoadInt64(&serviceQuit) == 1 {
			active = 0
		}

		if atomic.LoadInt64(&serviceActive) == 0 {
			active = 0
		}

		if active == 1 {
			sendBuf[0] = 't' // true
		} else {
			sendBuf[0] = 'f' // false
		}

		be.PutUint32(lenBuf, uint32(len(sendBuf)))

		lenBuf = lenBuf[:4]
		err = ztp.WriteN(c, lenBuf, 4)
		if err != nil {
			logger.Error("server send to client %s msg len failed, err: %s",
				c.RemoteAddr().String(), err.Error())
			break
		}

		err = ztp.WriteN(c, sendBuf, len(sendBuf))
		if err != nil {
			logger.Error("server send to client %s msg failed, err: %s",
				c.RemoteAddr().String(), err.Error())
			break
		}
	}
}
